<?php
/**
 * Created by PhpStorm.
 * User: 76587
 * Date: 2018-05-29
 * Time: 11:43
 */

namespace addons\auth\controllers;

use addons\auth\models\Login;
use Yii;
use apis\base\BaseController;
use yii\web\NotFoundHttpException;

class AuthController extends BaseController
{

    private $route = 'AuthLogic';

    public function actionLogin($service)
    {
        $post = Yii::$app->getRequest()->post();
        $model = new Login(['service' => $service]);

        if ($model->load([$model->formName() => $post]) && $model->login()) {
            $user = $model->getUser();
            $user->jwt = $user->getJWT(['ut' => $service]);
            return $user->toArray(['id', 'username', 'head', 'jwt']);
        } else {
            $errors = $model->firstErrors;
            throw new NotFoundHttpException(reset($errors));
        }
    }

    /**
     * Logout
     * @return string
     */
    public function actionLogout()
    {
        Yii::$app->getUser()->logout();
    }

    /**
     * Signup new user
     * @return string
     */
    public function actionSignup($service)
    {
        return Yii::$app->rpc->call($service, $this->route)->Signup(Yii::$app->getRequest()->post());
    }
}